import { computed, onMounted, onUnmounted, watch, ref } from 'vue'

function fixZero(num) {
  return num > 9 ? num : `0${num}`
}

function getNow() {
  return new Date().getTime() / 1000
}

export default (props) => {
  const now = ref(getNow())

  const end = computed(() => props.end_time || 0)

  const leaveArr = computed(() => {
    if (now.value >= end.value) return ['00', '00']
    const distance = ~~(end.value - now.value)
    const s = distance % 60
    const m = ~~(distance / 60)
    return [fixZero(m), fixZero(s)]
  })

  const isEnd = computed(() => {
    return leaveArr.value[0] === '00' && leaveArr.value[1] === '00'
  })

  let timer

  const clearTimer = () => {
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
  }

  const startTimer = () => {
    clearTimer()
    timer = setTimeout(() => {
      now.value = getNow()
      if (now.value > end.value) {
        clearTimer()
      } else {
        startTimer()
      }
    }, 1000)
  }

  watch(end, startTimer)
  onMounted(startTimer)
  onUnmounted(clearTimer)

  return {
    leaveArr,
    isEnd
  }
}

